"""
订单相关的数据验证模式
"""
from marshmallow import Schema, fields, validate, validates, ValidationError, post_load
from app.models.order import OrderStatus, PaymentStatus

class OrderItemSchema(Schema):
    """订单项数据验证模式"""
    id = fields.Integer(dump_only=True)
    product_id = fields.Integer(required=True)
    variant_id = fields.Integer()
    quantity = fields.Integer(required=True, validate=validate.Range(min=1))
    price = fields.Decimal(dump_only=True)
    subtotal = fields.Decimal(dump_only=True)
    created_at = fields.DateTime(dump_only=True)
    
    @validates('product_id')
    def validate_product_id(self, value):
        """验证商品ID"""
        from app.models.product import Product
        product = Product.query.get(value)
        if not product:
            raise ValidationError('商品不存在')
    
    @validates('variant_id')
    def validate_variant_id(self, value):
        """验证变体ID"""
        if not value:
            return
            
        from app.models.product import ProductVariant
        variant = ProductVariant.query.get(value)
        if not variant:
            raise ValidationError('商品变体不存在')
            
        # 检查变体是否属于指定的商品
        if variant.product_id != self.context.get('product_id'):
            raise ValidationError('商品变体不属于指定商品')
    
    @validates('quantity')
    def validate_quantity(self, value):
        """验证数量"""
        from app.models.product import Product, ProductVariant
        
        product_id = self.context.get('product_id')
        variant_id = self.context.get('variant_id')
        
        if variant_id:
            variant = ProductVariant.query.get(variant_id)
            if variant and variant.stock < value:
                raise ValidationError('商品变体库存不足')
        elif product_id:
            product = Product.query.get(product_id)
            if product and product.stock < value:
                raise ValidationError('商品库存不足')

class OrderSchema(Schema):
    """订单数据验证模式"""
    id = fields.Integer(dump_only=True)
    order_number = fields.String(dump_only=True)
    user_id = fields.Integer(dump_only=True)
    status = fields.String(dump_only=True)
    total_amount = fields.Decimal(dump_only=True)
    shipping_address = fields.String(required=True)
    shipping_method = fields.String(required=True)
    payment_method = fields.String(required=True)
    payment_status = fields.String(dump_only=True)
    notes = fields.String(allow_none=True)
    created_at = fields.DateTime(dump_only=True)
    items = fields.List(fields.Nested(OrderItemSchema), required=True, validate=validate.Length(min=1))
    
    @validates('items')
    def validate_items(self, value):
        """验证订单项"""
        if not value:
            raise ValidationError('订单至少需要一项商品')
            
        # 为每个订单项设置上下文
        for item in value:
            item_context = {}
            if 'product_id' in item:
                item_context['product_id'] = item['product_id']
            if 'variant_id' in item:
                item_context['variant_id'] = item['variant_id']
                
            self.context['item_context'] = item_context

class OrderUpdateSchema(Schema):
    """订单更新数据验证模式"""
    status = fields.String(validate=validate.OneOf([status.value for status in OrderStatus]))
    payment_status = fields.String(validate=validate.OneOf([status.value for status in PaymentStatus]))
    shipping_address = fields.String()
    shipping_method = fields.String()
    payment_method = fields.String()
    notes = fields.String(allow_none=True)

class OrderCreateSchema(Schema):
    """订单创建序列化模式"""
    shipping_address = fields.String(required=True)
    shipping_method = fields.String(required=True)
    payment_method = fields.String(required=True)
    notes = fields.String()
    items = fields.List(fields.Nested(OrderItemSchema), required=True)
    
    @validates('items')
    def validate_items(self, items):
        """验证订单项"""
        if not items or len(items) == 0:
            raise ValidationError('订单至少需要一项商品')

class OrderStatusUpdateSchema(Schema):
    """订单状态更新序列化模式"""
    status = fields.String(required=True, validate=validate.OneOf([
        'pending', 'confirmed', 'processing', 
        'shipped', 'delivered', 'completed', 
        'canceled', 'refunded'
    ]))
    
    # 可选字段，用于记录状态变更原因
    reason = fields.String()

class OrderBatchDeleteSchema(Schema):
    """订单批量删除序列化模式"""
    order_ids = fields.List(fields.Integer(), required=True)
    
    @validates('order_ids')
    def validate_order_ids(self, order_ids):
        """验证订单ID列表"""
        if not order_ids or len(order_ids) == 0:
            raise ValidationError('请提供要删除的订单ID列表') 